<template>
  <div class="admin-login-wrapper">
    <div class="login-form-title">管理员登录</div>
    <div class="login-form-sub-title">福农跑腿管理后台</div>
    <a-form ref="loginFormRef" :model="formData" class="login-form" layout="vertical" @submit="handleSubmit">
      <a-form-item
        field="username"
        :rules="[
          { required: true, message: '请输入用户名' },
          { minLength: 3, message: '用户名长度不能少于3位' },
          { maxLength: 50, message: '用户名长度不能超过50位' }
        ]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input v-model="formData.username" placeholder="请输入用户名" allow-clear size="large">
          <template #prefix>
            <icon-user />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item
        field="password"
        :rules="[
          { required: true, message: '请输入密码' },
          { minLength: 6, message: '密码长度不能少于6位' },
          { maxLength: 32, message: '密码长度不能超过32位' }
        ]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input-password v-model="formData.password" placeholder="请输入密码" allow-clear size="large">
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item
        field="captchaCode"
        :rules="[
          { required: true, message: '请输入验证码' },
          { minLength: 4, message: '验证码长度不能少于4位' }
        ]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <div class="captcha-container">
          <a-input
            v-model="formData.captchaCode"
            placeholder="请输入验证码"
            class="captcha-input"
            size="large"
            @press-enter="() => handleSubmit()"
          />
          <div class="captcha-image-wrapper" @click="refreshCaptcha">
            <img
              v-if="captchaImage"
              :src="captchaImage"
              alt="验证码"
              class="captcha-image"
              :class="{ loading: captchaLoading }"
            />
            <div v-else class="captcha-placeholder">
              <icon-refresh :class="{ 'animate-spin': captchaLoading }" />
              <span>点击获取</span>
            </div>
          </div>
        </div>
      </a-form-item>

      <a-space :size="16" direction="vertical">
        <div class="login-form-password-actions">
          <a-checkbox v-model="loginConfig.rememberPassword">记住密码</a-checkbox>
        </div>

        <a-button type="primary" html-type="submit" long size="large" :loading="loading">登录</a-button>
      </a-space>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import type { ValidatedError } from '@arco-design/web-vue/es/form/interface';
import { IconUser, IconLock, IconRefresh } from '@arco-design/web-vue/es/icon';
import { useStorage } from '@vueuse/core';
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';

import { authApi } from '@/api';
import type { AdminLoginRequest, CaptchaResponse } from '@/api/auth';
import { useUserStore } from '@/stores';

const router = useRouter();
const userStore = useUserStore();

// 响应式数据
const loginFormRef = ref();
const loading = ref(false);
const captchaImage = ref('');
const captchaLoading = ref(false);

// 登录配置（本地存储）
const loginConfig = useStorage('admin-login-config', {
  rememberPassword: true,
  username: '', // 生产环境应该为空
  password: '' // 生产环境应该为空
});

// 表单数据
const formData = reactive<AdminLoginRequest>({
  username: loginConfig.value.username,
  password: loginConfig.value.password,
  captchaId: '',
  captchaCode: ''
});

// 处理表单提交
const handleSubmit = async (params?: {
  errors: Record<string, ValidatedError> | undefined;
  values: Record<string, unknown>;
}) => {
  if (loading.value) return;

  // 如果没有参数，直接触发表单验证和提交
  if (!params) {
    loginFormRef.value?.validate(
      (errors: Record<string, ValidatedError> | undefined, values: Record<string, unknown>) => {
        handleSubmit({ errors, values });
      }
    );
    return;
  }

  const { errors } = params;

  if (!errors) {
    setLoading(true);

    try {
      // 确保使用当前表单数据而不是验证回调的values
      const loginData: AdminLoginRequest = {
        username: formData.username,
        password: formData.password,
        captchaId: formData.captchaId,
        captchaCode: formData.captchaCode
      };

      // 验证必填字段
      if (!loginData.username || !loginData.password || !loginData.captchaCode || !loginData.captchaId) {
        throw new Error('请填写完整的登录信息');
      }

      await userStore.adminLogin(loginData);

      // 记住密码处理
      const { rememberPassword } = loginConfig.value;
      loginConfig.value.username = rememberPassword ? loginData.username : '';
      loginConfig.value.password = rememberPassword ? loginData.password : '';

      // 跳转到首页或原来的页面
      const { redirect, ...othersQuery } = router.currentRoute.value.query;
      if (redirect) {
        // 如果有 redirect 参数，跳转到指定页面
        await router.push({
          path: redirect as string,
          query: {
            ...othersQuery
          }
        });
      } else {
        // 否则跳转到仪表板首页
        await router.push('/dashboard');
      }
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (err: unknown) {
      // 登录失败时刷新验证码
      await refreshCaptcha();
    } finally {
      setLoading(false);
    }
  }
};

// 设置加载状态
const setLoading = (value: boolean) => {
  loading.value = value;
};

// 获取验证码
const getCaptcha = async () => {
  if (captchaLoading.value) return;

  try {
    captchaLoading.value = true;
    const response: CaptchaResponse = await authApi.getCaptcha();

    if (response && response.captchaId && response.imageData) {
      formData.captchaId = response.captchaId;
      captchaImage.value = response.imageData;
    } else {
      throw new Error('验证码响应格式错误');
    }
  } catch (error) {
    console.error('获取验证码失败:', error);
  } finally {
    captchaLoading.value = false;
  }
};

// 刷新验证码
const refreshCaptcha = async () => {
  formData.captchaCode = '';
  await getCaptcha();
};

// 组件挂载
onMounted(() => {
  // 如果已经登录，直接跳转
  if (userStore.isLoggedIn) {
    router.replace('/dashboard');
  }
  // 获取验证码
  getCaptcha();
});
</script>

<style scoped lang="less">
.admin-login-wrapper {
  width: 320px;
}

.login-form {
  &-title {
    margin-bottom: 8px;
    color: var(--color-text-1);
    font-weight: 600;
    font-size: 28px;
    line-height: 36px;
    text-align: center;
  }

  &-sub-title {
    margin-bottom: 32px;
    color: var(--color-text-3);
    font-size: 16px;
    line-height: 24px;
    text-align: center;
  }

  &-error-msg {
    margin-bottom: 16px;
    padding: 8px 12px;
    color: rgb(var(--red-6));
    background-color: rgb(var(--red-1));
    border: 1px solid rgb(var(--red-3));
    border-radius: 6px;
    font-size: 14px;
    line-height: 20px;
    text-align: center;
  }

  &-password-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.captcha-container {
  display: flex;
  flex: 1;
  align-items: center;
  gap: 8px;

  .captcha-input {
    flex: 1;
  }

  .captcha-image-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 36px;
    cursor: pointer;
    border: 1px solid var(--color-border);
    background-color: var(--color-fill-1);
    transition: all 0.2s;
    flex-shrink: 0;

    &:hover {
      border-color: var(--color-border-2);
      background-color: var(--color-fill-2);
    }
  }

  .captcha-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: opacity 0.2s;

    &.loading {
      opacity: 0.6;
    }
  }

  .captcha-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    color: var(--color-text-3);
    font-size: 12px;

    .arco-icon {
      margin-bottom: 2px;
      font-size: 14px;
    }

    .animate-spin {
      animation: spin 1s linear infinite;
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
